package org.stvd.common.security.support;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.stvd.common.Consts;
import org.stvd.core.util.DateUtil;
import org.stvd.entities.admin.Roles;
import org.stvd.entities.admin.UserBase;
import org.stvd.entities.admin.Users;
import org.stvd.service.admin.RolesService;
import org.stvd.service.admin.UsersService;

public class UserDetailService implements UserDetailsService {

    private UsersService usersService;
    
    private RolesService rolesService;

    public UsersService getUsersService() {
        return usersService;
    }

    public void setUsersService(UsersService usersService) {
        this.usersService = usersService;
    }
    
    public RolesService getRolesService() {
        return rolesService;
    }

    public void setRolesService(RolesService rolesService) {
        this.rolesService = rolesService;
    }

    // 登录验证
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        Users users = this.usersService.findById(userId);
        if (users == null) {
            throw new UsernameNotFoundException("登录名或密码错误");
        }
        boolean enables = "T".equals(users.getEnable().toUpperCase());
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;
        // 封装到UserDetail
        UserDetail userdetail = new UserDetail(users.getUserId(), users.getPwd(), enables, accountNonExpired,
                credentialsNonExpired, accountNonLocked, null);
        userdetail.setUsers(users);
        userdetail.setLoginTime(DateUtil.getSystemDate());
        return userdetail;
    }

    // 取得用户的角色权限
    public void obtionGrantedAuthorities(UserDetail userdetail) {
        List<GrantedAuthority> authSet = new ArrayList<GrantedAuthority>();
        List<Roles> roles = rolesService.getRolesByUserId(userdetail.getUsername(), Consts.GUID);
        if(roles!=null && roles.size() > 0) {
            for (Roles role : roles) {
                authSet.add(new SimpleGrantedAuthority(role.getRoleCode()));
            }
        }
        userdetail.setAuthorities(authSet);
    }

    public void loadUserDetailPlus(UserDetail userdetail) {
        userdetail.setRemarks(this.usersService.setUserDetailPlus(userdetail.getUsername()));
        if (userdetail.getRemarks().containsKey("userBase")) {
            userdetail.setUserBase((UserBase) userdetail.getRemarks().get("userBase"));
        }
    }
}
